<template>
  <!-- header -->
  <div class="app-header">
    <!-- logo -->
    <div class="header-left">
      <div class="header-left-logo">
        <img src="./assets/logo.png" />
        <span>网易云音乐</span>
      </div>
      <div class="header-search">
        <span @click="goBack('left')">
          <i class="iconfont icon-xiangzuo"></i>
        </span>
        <span @click="goBack('right')">
          <i class="iconfont icon-xiangyou1"></i>
        </span>
        <div class="header-search-box">
          <!-- 搜索建议 -->
          <div class="suggest-box" v-show="suggestIsShow" @mouseenter="holdShowFalse('hold')" @mouseleave="holdShowFalse('no')">
            <!-- 详细列表 -->
            <div class="box-hot">热搜榜</div>
            <div class="suggest-list" v-for="(item, index) in suggestData" :key="index" @click="searchSong(item.searchWord)">
              <div class="list-ranking" :style="index < 3 ? 'color : red' : 'color :#cccccc'">
                {{ index + 1 }}
              </div>
              <div class="list-con">{{ item.searchWord }}</div>
              <div class="list-hot">{{ item.score }}</div>
            </div>
            <div></div>
          </div>

          <i class="iconfont icon-sousuo"></i>
          <input type="text" placeholder="周杰伦" @focus="showSuggest('show')" @blur="showSuggest('hidd')" @keydown.enter="searchSong('key')" v-model="keyWords" />
        </div>
      </div>
    </div>
    <div class="header-right">
      <div class="header-right-headpic" @click="loginOrExit">
        <!-- 未登录 -->
        <img src="./assets/nolog.png" v-if="cookie.length < 5" />
        <img :src="userInfo.avatarUrl" v-else />
      </div>
      <div @click="()=>{show = true,eLoginShow = false}">
        <span v-if="cookie.length < 5">未登录</span>
        <span v-else>{{ userInfo.nickname }}</span>
      </div>
      <div v-if="cookie.length > 5">开通CVIP</div>
    </div>
  </div>
  <van-overlay :show="show" @click="show = false" class="login-box">
    <!-- 登录窗口 -->
    <div class="login-window" @click.stop>
      <div>
        <img src="./assets/log-window.png" alt="" />
      </div>
      <!-- 手机验证码区域 -->
      <div class="winodw-login" v-if="!eLoginShow">
        <div>
          <i class="iconfont icon-phone"></i>
          <input type="text" placeholder="请输入手机号" v-model="phone" />
        </div>
        <div>
          <i class="iconfont icon-mima"></i>
          <input type="text" placeholder="请输入验证码" v-model="verificationNum" />
          <span @click="getPhoneCode">{{ preinstallText }}</span>
        </div>
      </div>
      <!-- 登录按钮 -->
      <div class="window-login-button-box" v-if="!eLoginShow">
        <van-button type="danger" @click="verificationPreinstall" class="window-login-button">登 录</van-button>
      </div>
      <!-- 其他登录方式 -->
      <!-- <div class="other-login">
          微信
          <span>
            <svg class="icon" aria-hidden="true">
              <use xlink:href="#icon-weixindenglu"></use>
            </svg>
          </span>
        </div> -->
      <!-- 底部用户协议 -->
      <div class="user-agreement" v-if="!eLoginShow">
        <van-checkbox v-model="logChecked" checked-color="#ee0a24"></van-checkbox>
        <span>同意<strong>《服务条款》</strong><strong>《隐私条款》</strong><strong>《儿童隐私条款》</strong></span>
      </div>
      <!-- 二维码登录 -->
      <div v-else>
        <img :src="imgE" alt="" width="300" height="300">
      </div>
      <!-- 其他登录方式 -->
      <div class="get-other">
        <span @click="getE">选择其他登录方式</span>
      </div>
    </div>
  </van-overlay>

  <!-- 左侧tab栏 -->
  <tab-subfield></tab-subfield>

  <!-- 底部播放器 -->
  <player-vue></player-vue>
  <router-view></router-view>
</template>

<script setup>
import { ref, computed, watch } from "vue";
import { useRouter } from "vue-router";
import { Toast } from "vant";
import { useStore } from "vuex";
import { Dialog } from "vant";
import axios from "axios";
import "./assets/fonts/window-login/iconfont";
import TabSubfield from "./components/TabSubfield/TabSubfield.vue";
import playerVue from "./components/player/player.vue";

const router = useRouter();
const store = useStore();

// 控制搜索建议显示变量
const suggestIsShow = ref(false);
// 搜索建议数据
const suggestData = ref("");
// 阻止事件变量
const holdData = ref(false);

// 显示搜索建议
const showSuggest = (isShow) => {
  if (isShow == "show") {
    suggestIsShow.value = true;
    // 获取搜索建议
    axios
      .get(`http://localhost:3000/search/hot/detail`)
      .then((res) => {
        suggestData.value = res.data.data;
      })
      .catch((err) => {
        console.log(`获取搜索建议失败${err}`);
      });
  } else {
    if (holdData.value) return (suggestIsShow.value = true);
    return (suggestIsShow.value = false);
  }
};

// 阻止窗口关闭（变量）
const holdShowFalse = (flag) => {
  if (flag == "hold") return (holdData.value = true);
  return (holdData.value = false);
};

// 左右箭头回退
const goBack = (str) => {
  if (str == "left") return router.go(-1);
  return router.go(1);
};

// 搜索框关键字
let keyWords = ref("");

// 搜索框回车搜索
const searchSong = (keyStr) => {
  // 关闭搜索建议框
  suggestIsShow.value = false;

  console.log(keyStr);
  if (keyStr != "key") {
    keyWords.value = keyStr;
  }
  if (keyWords.value == "") {
    keyWords.value = "周杰伦";
  }
  // 更改vuex中search值
  store.commit("m_search/updateSearchTitle", keyWords.value.trim());
  if (router.currentRoute.value.path == "/search-info-list/searchSingle") {
    console.log("局部刷新");
    // 刷新页面 体验不好 性能消耗
    // window.location.reload()

    // 跳转到空白路由 实现局部刷新
    router.push({
      name: "refresh",
    });

    return;
  }

  router.push({
    name: "searchInfoList",
    params: {
      title: keyWords.value,
    },
  });
};

// 点击头像
const loginOrExit = () => {
  if (cookie.value.length < 5) return (show.value = true);
  Dialog.confirm({
    title: "提示",
    message: "确认退出吗？",
  })
    .then(() => {
      // 清空 cookie
      cookie.value = "";
      store.commit("m_user/updatecookie", "");
      Toast("退出成功");
      setTimeout(() => {
        router.push({
          name: "refresh",
        });
      }, 500);
    })
    .catch(() => {
      console.log("用户取消退出");
    });
};

// 登录遮罩层
const show = ref(false);

// 获取登录状态或者登录信息
const getLogInfo = () => {
  show.value = true;
};

// 用户协议
const logChecked = ref(false);

// 手机号
const phone = ref("");
// 获取验证码
const getPhoneCode = () => {
  // 判断是否在60秒冷却内
  if (preinstallText.value != "获取验证码") {
    return;
  }

  // 请求获取验证码
  axios
    .get(`/captcha/sent?phone=${phone.value}`)
    .then((res) => {
      console.log(res);
      if (res.data.code != 200) return Toast(`${res.data.message}`);
      countDown();
    })
    .catch((err) => {
      Toast("验证码获取失败!");
    });
};
// 获取验证码按钮文本
const preinstallText = ref("获取验证码");
// 预设60秒
const preinstallSecond = ref(60);
// 倒计时60秒
const countDown = () => {
  const timer = setInterval(() => {
    if (preinstallSecond.value == 0) {
      clearInterval(timer);
      preinstallSecond.value = 60;
      return;
    }
    preinstallSecond.value--;
    // 验证码文本
    if (preinstallSecond.value < 60 && preinstallSecond.value > 0) {
      preinstallText.value = `${preinstallSecond.value}秒`;
    } else {
      preinstallText.value = "获取验证码";
    }
  }, 1000);
};

// 用户信息详情
const userInfo = ref("");
const OldUserInfo = computed(() => {
  return store.state.m_user.userInfo;
});
userInfo.value = OldUserInfo.value;
// 获取用户登录凭证
const cookie = computed(() => {
  return store.state.m_user.cookie;
});

// 输入框验证码
const verificationNum = ref("");
// 验证验证码
const verificationPreinstall = () => {
  if (logChecked.value == false) return Toast("请先同意用户协议");

  // 登录 /login/cellphone?phone=${phone.value}&captcha=${verificationNum.value}
  // 游客登录 /register/anonimous
  axios
    .get(`/register/anonimous`)
    .then((res) => {
      Toast("验证通过 ~");
      // 清空验证码栏
      verificationNum.value = "";
      /**
       * 游客登录
       */
      // 更改 store 中 userInfo 的值
      store.commit("m_user/updateUserInfo", res.data.profile);
      // 登录验证通过
      userInfo.value = res.data.profile;
      console.log(userInfo.value);

      // 更改 store 中 cookie 的值
      store.commit("m_user/updatecookie", res.data.cookie);
      show.value = false;

      // 延时跳转
      setTimeout(() => {
        router.push({
          name: "refresh",
        });
      }, 500);
    })
    .catch((err) => {
      console.log(err);
      Toast("登录验证码错误");
    });
};

// 二维码登录
const eLoginShow = ref(false);
const imgE = ref();
const getE = async () => {
  eLoginShow.value = !eLoginShow.value;
  await axios
    .get(`/login/qr/key?&timestamp=${new Date().valueOf()}`)
    .then(async (res) => {
      let key = res.data.data.unikey;
      await axios
        .get(
          `/login/qr/create?key=${key}&qrimg=true&timestamp=${new Date().valueOf()}`
        )
        .then((res) => {
          imgE.value = res.data.data.qrimg;

          let timer = setInterval(async () => {
            await axios
              .get(
                `/login/qr/check?key=${key}&timestamp=${new Date().valueOf()}`
              )
              .then(async (res) => {
                let uid;
                if (res.data.code === 803) {
                  clearInterval(timer);
                  store.commit("m_user/updatecookie", res.data.cookie);
                  show.value = false;
                  await axios.get(`/login/status`).then(async (res) => {
                    console.log(res);
                    uid = res.data.data.account.id;
                    await axios
                      .get(
                        `/user/account?uid=${uid}&cookie=${store.state.m_user.cookie}`
                      )
                      .then((res) => {
                        // 更改 store 中 userInfo 的值
                        store.commit("m_user/updateUserInfo", res.data.profile);
                        // 登录验证通过
                        userInfo.value = res.data.profile;
                      });
                  });
                  // 延时跳转
                  setTimeout(() => {
                    router.push({
                      name: "refresh",
                    });
                  }, 500);
                }
              });
          }, 2000);

          watch(
            () => show.value,
            () => {
              if (show.value === false) {
                clearInterval(timer);
              }
            }
          );
        });
    });
};
</script>
<style lang="less">
// 清除默认样式
@import url(./assets/normalize.css);
@import url(./assets/fonts/iconfont.css);
@import url(./assets/fonts/window-login/iconfont.css);

.van-overlay {
  z-index: 2000;
  display: flex;
  justify-content: center;
  align-items: center;

  .login-window {
    padding: 50px;
    padding-bottom: 27px;
    height: 450px;
    width: 300px;
    background-color: white;
    display: flex;
    flex-wrap: wrap;
    flex-direction: column;

    div {
      flex: 1;

      img {
        width: 100%;
      }
    }

    .winodw-login {
      border: 1px solid rgba(0, 0, 0, 0.103);
      border-radius: 6px;
      margin-top: 30px;
      display: flex;
      flex-direction: column;
      flex-wrap: wrap;

      div {
        position: relative;
        flex: 1;
        padding: 10px;
        display: flex;

        &:nth-child(1) {
          border-bottom: 1px solid rgba(0, 0, 0, 0.103);
        }

        &:nth-child(2) {
          span {
            position: absolute;
            width: 66px;
            right: 10px;
            top: 15px;
            color: #818181;

            &:hover {
              cursor: pointer;
            }
          }
        }

        input {
          border: none;
          outline: none;
          width: 90%;
          height: 100%;
          margin-left: 6px;

          &::-webkit-input-placeholder {
            color: #b3b3b3;
            padding-left: 2px;
          }
        }
      }
    }

    .window-login-button-box {
      .window-login-button {
        margin-top: 26px;
        width: 100%;
        border-radius: 6px;
        background-color: #ea4848;
        transition: all 0.3s;

        &:hover {
          background-color: red;
        }
      }
    }

    .other-login {
      flex: 0.5;
      display: flex;
      justify-content: center;
      align-items: center;
      height: 50px;

      span {
        &:hover {
          cursor: pointer;
        }
        svg {
          width: 40px;
        }
      }
    }

    .user-agreement {
      flex: 0.5;
      display: flex;
      justify-content: center;
      align-items: center;

      span {
        strong {
          color: #507daf;
          font-weight: 400;
          &:hover {
            cursor: pointer;
          }
        }
      }
    }

    .get-other {
      display: flex;
      justify-content: center;
      flex: 0.5;

      &:hover {
        cursor: pointer;
      }
    }
  }
}

.app-header {
  z-index: 999;
  position: fixed;
  top: 0;
  width: 100%;
  height: 60px;
  background-color: #ec4141;
  display: flex;
  justify-content: space-between;

  .header-left {
    line-height: 60px;
    width: 470px;
    display: flex;

    .header-left-logo {
      margin-left: 10px;
      width: 120px;
      display: flex;
      justify-content: space-around;
      align-items: center;
      &:hover {
        cursor: pointer;
      }

      span {
        font-size: 17px;
        color: #ffffff;
        font-family: "幼圆";
      }
    }

    .header-search {
      margin-left: 30px;
      display: flex;
      width: 280px;
      justify-content: space-around;
      align-items: center;

      span {
        width: 26px;
        height: 26px;
        border-radius: 13px;
        background-color: rgba(0, 0, 0, 0.096);
        display: flex;
        justify-content: center;
        align-items: center;
        &:hover {
          cursor: pointer;
        }
      }

      .header-search-box {
        position: relative;
        width: 190px;
        height: 35px;
        background-color: rgba(0, 0, 0, 0.082);
        border-radius: 30px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        transition: all 0.1s;

        .suggest-box {
          overflow-y: scroll;
          //设置滚动条整体样式
          &::-webkit-scrollbar {
            width: 6px;
          }

          // 滚动条颜色
          &::-webkit-scrollbar-thumb {
            border-radius: 10px;
            -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.13);
            background-color: #e0e0e0 !important;
          }
          // 未滚动的颜色
          &::-webkit-scrollbar-track {
            -webkit-box-shadow: inset 0 0 5px rgb(0 0 0 / 20%);
            border-radius: 0;
            // background: rgba(255, 0, 0, 0.89);
          }

          position: absolute;
          width: 350px;
          height: 799px;
          background-color: rgb(255, 255, 255);
          top: 52px;
          left: -28px;
          box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
          border-radius: 6px;
          display: flex;
          flex-direction: column;
          transition: all 0.2s;

          .box-hot {
            margin-left: 20px;
            font-size: 14px;
            color: #00000087;
          }

          .suggest-list {
            display: flex;
            padding: 10px 20px;
            line-height: 40px;

            &:hover {
              cursor: pointer;
              background-color: #f3f3f3;
            }

            .list-ranking {
              margin-right: 20px;
              font-size: 16px;
            }

            .list-con {
              color: rgba(0, 0, 0, 0.733);
              font-weight: 900;
              margin-left: 4px;
            }

            .list-hot {
              margin-left: 10px;
              color: #cccccc;
            }
          }
        }

        i {
          margin-left: 10px;
        }
        input {
          width: 160px;
          border: none;
          color: white;
          outline: none;
          background: none;
          // 更改输入框提示文字样式
          &::-webkit-input-placeholder {
            color: #ec8787;
          }
        }
      }
    }
  }
  .header-right {
    margin-right: 20px;
    // width: 140px;
    display: flex;
    color: rgb(230, 230, 230);
    align-items: center;
    justify-content: space-around;

    div {
      margin-right: 8px;
    }
    .header-right-headpic {
      width: 30px;
      height: 30px;
      &:hover {
        cursor: pointer;
      }

      img {
        width: 100%;
        height: 100%;
        border-radius: 15px;
      }
    }
  }
}
</style>